import api from '@/api/index.js'

const methods = {}

methods.renderImage = (url) => {
	return new Promise((resolve) => {
		wx.getImageInfo({
			src: url,
			success: (res) => {
				resolve(res.path)
			}
		});
	})
}

// 深度克隆
methods.deepClone = (obj) => {
	// 处理基本类型和 null
	if (obj === null || typeof obj !== 'object') {
		return obj;
	}

	// 处理数组
	if (Array.isArray(obj)) {
		return obj.map(item => methods.deepClone(item));
	}

	// 处理对象
	const clonedObj = {};
	for (const key in obj) {
		if (obj.hasOwnProperty(key)) {
			clonedObj[key] = methods.deepClone(obj[key]);
		}
	}

	// 处理函数
	if (typeof obj === 'function') {
		return obj.bind(clonedObj);
	}

	return clonedObj;
}

methods.login = () => {
	return new Promise((resolve) => {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				let params = {
					code: res.code,
				}
				api.get('/system/user/wxLogin', params).then(res => {
					uni.setStorageSync('token', res.token)
					resolve(1)
				})
			},
			fail: (err) => {
				console.log(err)
			}
		})
	})
}

/**
 * 将字符串转换为偏深蓝色系的深色16进制颜色
 * @param {string} str - 输入字符串
 * @param {number} [minBlue=100] - 蓝色分量最小值 (0-255)
 * @param {number} [maxRed=150] - 红色分量最大值 (0-255)
 * @param {number} [maxGreen=180] - 绿色分量最大值 (0-255)
 * @returns {string} 16进制颜色字符串（#RRGGBB）
 */
methods.stringToColor = (str, minBlue = 100, maxRed = 150, maxGreen = 180) => { // 哈希计算确保分布均匀
	let hash = 0;
	for (let i = 0; i < str.length; i++) {
		const char = str.charCodeAt(i);
		hash = ((hash << 7) - hash) + char;
		hash |= 0; // 保持32位整数特性
	}
	const unsignedHash = Math.abs(hash) >>> 0;

	// 生成基础颜色分量
	let r = (unsignedHash >> 16) & 0xFF;
	let g = (unsignedHash >> 8) & 0xFF;
	let b = unsignedHash & 0xFF;

	// 颜色调整：限制红绿色，确保蓝色主导，同时提高亮度
	r = Math.min(r, maxRed); // 限制红色，避免偏紫
	g = Math.min(g, maxGreen); // 适度限制绿色
	b = Math.max(b, minBlue); // 确保足够的蓝色分量

	// 提高亮度但保持蓝色基调
	const brightnessBoost = 0.95; // 亮度提升系数
	r = Math.round(r * brightnessBoost);
	g = Math.round(g * brightnessBoost);
	b = Math.round(b * brightnessBoost);

	// 确保所有分量在有效范围内
	r = Math.max(0, Math.min(255, r));
	g = Math.max(0, Math.min(255, g));
	b = Math.max(0, Math.min(255, b));

	// 转换为16进制格式
	const toHex = (value) => {
		return value.toString(16)
			.padStart(2, '0')
			.slice(-2)
			.toLowerCase();
	};

	return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}

methods.getStatus = (size, total) => {
	if(total <= size) {
		return 'nomore'
	}else {
		return 'loadmore'
	}
}

export default methods